package com.zzz.ssh.component.config;


import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import com.zzz.ssh.component.properties.ZzzSshProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import java.io.IOException;

@EnableConfigurationProperties({ZzzSshProperties.class})
@Configuration
public class SshConfig {

    @Bean
    public Connection connect(ZzzSshProperties zzzSshProperties) throws IOException {

        Connection connection = new Connection(zzzSshProperties.getHost());
        connection.connect();
        if (connection.authenticateWithPassword(zzzSshProperties.getUsername(), zzzSshProperties.getPassword())) {
            return connection;
        }
        throw new RuntimeException("connection fail");
    }

    @Bean
    @Scope(value = "prototype")
    public Session session(Connection connect) throws IOException {
        return connect.openSession();
    }
}
